import 'dart:io' show Platform;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart'
    show
        BMFCoordinate,
        BMFMapSDK,
        BMFMapType,
        BMFUserTrackingMode,
        BMF_COORD_TYPE;
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:get/get.dart';
import 'package:smart_shoes/define/define_colors.dart';
import 'package:smart_shoes/module/map/custom_widgets/map_base_page_state.dart';
import 'package:smart_shoes/module/map/map/map_widget.dart';
import 'package:smart_shoes/router/app_router.dart';
import 'package:smart_shoes/tools/screen_tool.dart';
import 'package:smart_shoes/tools/widget_tools.dart';

/// 地图页面组件，用于展示地图相关功能界面
class MapPage extends StatefulWidget {
  const MapPage({super.key});

  @override
  State<MapPage> createState() => _MapPageState();
}

class _MapPageState extends BMFBaseMapState<MapPage> {
  /// 定位模式状态
  bool _showUserLocaion = true;

  /// 定位模式状态

  /// 我的位置
  BMFUserLocation? _userLocation;
  // 新增：用户是否同意隐私政策
  bool _isPrivacyAgreed = false;

  /// 定位模式
  BMFUserTrackingMode _userTrackingMode = BMFUserTrackingMode.None;

  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();

  // 常量部分，集中管理配置信息
  static const double kEquipmentViewHeight = 213;
  static const String kIosApiKey = 'HWr0m9L6PGJ0VW9nneu1OslxKx9xbPIQ';
  static const BMF_COORD_TYPE kMapCoordType = BMF_COORD_TYPE.BD09LL;
  static const Map<String, String> kDeviceInfo = {
    '设备名称：': '李文翰',
    '设备编号：': '2341343245',
    '所在城市：': '北京市朝阳区',
    '学校名称：': '北京市广渠门中学',
    '在校时间：': '2025-3-10 11:00-16:00',
  };
  static const List<Map<String, dynamic>> kTabBarItems = [
    {
      'title': '一键报警',
      'imagePath': 'assets/images/travel_path.png',
      'width': 24.0,
      'height': 24.0,
    },
    {
      'title': '距离预警',
      'imagePath': 'assets/images/range_warning.png',
      'width': 24.0,
      'height': 24.0,
    },
    {
      'title': '一键报警',
      'imagePath': 'assets/images/One-click_alarm.png',
      'width': 23.0,
      'height': 23.0,
    },
    {
      'title': '危险预警',
      'imagePath': 'assets/images/danger_warning.png',
      'width': 23.0,
      'height': 23.0,
    },
  ];

  BMFMapController? _mapController;
  final List<BMFOverlay> _overlays = [];

  @override
  void initState() {
    super.initState();
    // requestPermission();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_mapController != null) {
        _updateUserLocationDisplayParam();
        print('延迟更新用户位置图标');
      }
    });

    ///从网上拉数据
  }

  _getUserPhoneLocation() {
    final Map<String, Object> options = {
      'coorType': 'bd09ll', // 坐标类型
      'scanSpan': 1000, // 定位间隔，单位毫秒
      'openGps': true, // 开启 GPS
      'locationMode': 'Hight_Accuracy', // 定位模式
    };
    //  _myLocPlugin.prepareLoc(options);
    _myLocPlugin.startLocation();
  }

  /// 计算地图视图高度
  /// 返回地图视图的高度，通过屏幕高度减去底部安全区域高度、设备视图高度和导航栏高度得出
  double get _mapViewHeight {
    // 集中计算地图视图高度，提高可读性和可维护性
    final double screenHeight = ScreenTool.screenHeight;
    final double bottomSafeHeight = ScreenTool.bottomSafeHeight;
    final double navigationBarHeight = ScreenTool.navigationBarHeight;

    return screenHeight -
        bottomSafeHeight -
        kEquipmentViewHeight -
        navigationBarHeight;
  }

  @override
  void dispose() {
    super.dispose();
    _myLocPlugin.stopLocation();
    _myLocPlugin.stopUpdatingHeading();
  }

  void updateUserHeading(BaiduHeading heading) {
    if (Platform.isAndroid) {
      //android需要通过course设置方向
      _userLocation!.location!.course = heading.trueHeading;
    }
    BMFUserLocation userLocation = BMFUserLocation(
      //将包含course的BMFLocation对象传值给BMFUserLocation
      location: _userLocation!.location,
      //下面均是iOS的参数，iOS通过heading设置方向
      heading: BMFHeading.fromMap(heading.getMap()),
      title: '我是title',
    );
    _mapController?.updateLocationData(userLocation);
  }

  /// 更新位置
  void updateUserLocation(BaiduLocation result) {
    BMFCoordinate coordinate = BMFCoordinate(
      result.latitude!,
      result.longitude!,
    );

    BMFLocation location = BMFLocation(
      coordinate: coordinate,
      altitude: result.altitude,
      course: result.course,
      accuracy: result.radius,
      horizontalAccuracy: result.horizontalAccuracy,
      verticalAccuracy: result.verticalAccuracy,
    );

    BMFUserLocation userLocation = BMFUserLocation(location: location);
    _userLocation = userLocation;
    updateSelfUserLocation(result);
    _mapController?.updateLocationData(_userLocation!);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // 定义常量来管理定位数值，提高代码可维护性
    const double rightPadding = 12;
    const double leftPadding = 12;
    const double bottomOffset = 11;
    print(" build - 接受定位回调 $_myLocPlugin");
    print(" build - 接受定位回调 $_myLocPlugin.toString");

    ///接受定位回调
    _myLocPlugin.seriesLocationCallback(
      callback: (BaiduLocation result) {
        print('收到定位数据: ${result.latitude}, ${result.longitude}');
        setState(() {
          updateUserLocation(result);
        });
        print(" seriesLocationCallback - 接受定位回调");
        setState(() {
          updateUserLocation(result);
        });
      },
    );

    _myLocPlugin.updateHeadingCallback(
      callback: (BaiduHeading heading) {
        setState(() {
          updateUserHeading(heading);
        });
      },
    );

    return Scaffold(
      // 使用 Stack 布局来重叠多个子组件
      body: Stack(
        children: [
          // 垂直排列地图视图和设备视图
          Column(
            children: [
              Container(height: _mapViewHeight),
              // MapWidget(height: _mapViewHeight, onMapCreated: f_onBMFMapCreated),
              _buildEquipmentView(),
            ],
          ),
          // 定位标签栏到右上角
          Positioned(
            right: rightPadding,
            top: ScreenTool.navigationBarHeight,
            child: _buildTabBar(),
          ),
          // 定位开关视图到左下角
          Positioned(
            left: leftPadding,
            bottom: _mapViewHeight - kEquipmentViewHeight + bottomOffset,
            child: _buildSwitchView(),
          ),
        ],
      ),
    );
  }

  /// 构建地图视图
  Widget _buildMapView() {
    return Container(
      width: double.infinity,
      height: _mapViewHeight,
      // child: BMFMapWidget(
      //   onBMFMapCreated: _onBMFMapCreated,
      //   mapOptions: _initMapOptions(),
      // ),
    );
  }

  // /// 初始化地图选项
  BMFMapOptions _initMapOptions() {
    return BMFMapOptions(
      center: BMFCoordinate(40.055101313423215, 116.43356500172574),

      zoomLevel: 15,
      mapType: BMFMapType.Standard,
    );
  }

  /// 构建设备视图
  Widget _buildEquipmentView() {
    return Container(
      padding: const EdgeInsets.only(top: 11.5),
      height: kEquipmentViewHeight,
      width: double.infinity,
      child: Column(
        children: [
          _buildEquipmentHeader(),
          const SizedBox(height: 8),
          _buildDeviceInfo(),
        ],
      ),
    );
  }

  /// 构建设备视图头部
  Widget _buildEquipmentHeader() {
    return Container(
      margin: const EdgeInsets.only(top: 11.5),
      height: 25,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text(
            '当前设备',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
          ),
          _buildAddDeviceButton(),
        ],
      ),
    );
  }

  /// 构建添加设备按钮
  Widget _buildAddDeviceButton() {
    return GestureDetector(
      onTap: _onAddDeviceTap,
      child: Container(
        margin: const EdgeInsets.only(right: 12),
        padding: const EdgeInsets.only(left: 12),
        width: 91,
        height: 25,
        decoration: BoxDecoration(
          color: CustomColors.containerColor,
          borderRadius: BorderRadius.circular(12.5),
        ),
        child: Row(
          children: [
            const Text(
              '添加设备',
              style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
            ),
            Image.asset('assets/images/add.png'),
          ],
        ),
      ),
    );
  }

  /// 添加设备按钮点击事件处理
  void _onAddDeviceTap() {
    print('点击了添加设备按钮');
    // 可在此处添加实际添加设备的业务逻辑
    Get.toNamed(AppRoutes.addDevice);
  }

  /// 构建设备信息视图
  Widget _buildDeviceInfo() {
    return Container(
      margin: const EdgeInsets.only(left: 12, right: 91.5),
      height: 112,
      child: Row(
        children: [
          _buildDeviceImage(),
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.zero,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount: kDeviceInfo.length,
              itemBuilder: (context, index) {
                final title = kDeviceInfo.keys.elementAt(index);
                final content = kDeviceInfo.values.elementAt(index);
                return _buildDeviceInfoItem(title, content);
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建设备图片视图
  Widget _buildDeviceImage() {
    return Container(
      width: 57,
      height: 57,
      child: Image.asset(
        'assets/images/yundongxie.png',
        width: 40.49,
        height: 23,
        fit: BoxFit.fitWidth,
      ),
    );
  }

  /// 构建设备信息列表项视图
  Widget _buildDeviceInfoItem(String title, String content) {
    return Container(
      // color: Colors.amber,
      height: 16,
      // padding: const EdgeInsets.symmetric(vertical: 8),
      margin: const EdgeInsets.only(bottom: 1),
      child: Row(
        children: [
          Text(
            title,
            style: const TextStyle(fontSize: 13, color: CustomColors.textColor),
          ),
          Expanded(
            child: Text(
              content,
              style: const TextStyle(
                fontSize: 13,
                color: CustomColors.textColor,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建开关视图
  Widget _buildSwitchView() {
    const double kContainerWidth = 123;
    const double kContainerHeight = 31;
    const double kPadding = 8;
    const double kBorderRadius = 8;
    const double kTextFontSize = 12;

    const Color kActiveSwitchColor = Colors.white;
    const Color kActiveTrackSwitchColor = CustomColors.switchColor;
    final Color kInactiveSwitchColor = Colors.grey;
    final Color? kInactiveTrackSwitchColor = Colors.grey[300];

    return Container(
      width: kContainerWidth,
      height: kContainerHeight,
      padding: EdgeInsets.all(kPadding),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kBorderRadius),
      ),
      child: Row(
        children: [
          Text(
            '开启中',
            style: TextStyle(
              fontSize: kTextFontSize,
              color: CustomColors.textColor,
            ),
          ),
          Switch(
            value: true,
            onChanged: _onSwitchChanged,
            activeColor: kActiveSwitchColor,
            activeTrackColor: kActiveTrackSwitchColor,
            inactiveThumbColor: kInactiveSwitchColor,
            inactiveTrackColor: kInactiveTrackSwitchColor,
          ),
        ],
      ),
    );
  }

  /// 开关状态改变事件处理
  void _onSwitchChanged(bool newValue) {
    setState(() {
      // 可在此处添加开关状态改变时的业务逻辑
      // CustomAlertDialog();

      _showCustomAlertDialog(context);
    });
  }

  /// 显示自定义弹窗
  void _showCustomAlertDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return WidgetTools().customAlertContent(context, (a) {}, () {
          // 你可以在这里添加更多处理逻辑
        });
      },
    );
  }

  /// 构建标签栏视图
  Widget _buildTabBar() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: CustomColors.boxShadowColor,
            spreadRadius: 0,
            blurRadius: 4,
          ),
        ],
      ),
      width: 54,
      height: 205,
      padding: const EdgeInsets.symmetric(horizontal: 7),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children:
            kTabBarItems
                .map(
                  (item) => _buildTabBarItem(
                    title: item['title'] as String,
                    imagePath: item['imagePath'] as String,
                    width: item['width'] as double,
                    height: item['height'] as double,
                  ),
                )
                .toList(),
      ),
    );
  }

  /// 构建标签栏单项视图
  Widget _buildTabBarItem({
    required String title,
    required String imagePath,
    required double width,
    required double height,
  }) {
    return GestureDetector(
      onTap: () {
        if (title == "危险预警") {
          Get.toNamed(AppRoutes.dsangerWarningPage);
        }
      },
      child: Column(
        children: [
          Image.asset(
            imagePath,
            width: width,
            height: height,
            fit: BoxFit.fitHeight,
          ),
          Text(
            title,
            style: TextStyle(fontSize: 8, color: CustomColors.textColor),
          ),
          const SizedBox(height: 8),
        ],
      ),
    );
  }

  /// 地图创建回调
  void _onBMFMapCreated(BMFMapController controller) {
    print('地图控制器已创建');
    _mapController = controller;
    _setupMapCallbacks();
    _addMapOverlays();
    _myLocPlugin.startLocation();
    _mapController?.showUserLocation(true);
    _updateUserLocation();
    // 增加更长的延迟并添加详细日志
    Future.delayed(Duration(seconds: 1), () {
      print('开始执行延迟更新...');
      _updateUserLocationDisplayParam();
      print('延迟更新执行完成');
    });
  }

  BaiduLocationIOSOption _initIOSOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
      coordType: BMFLocationCoordType.bd09ll, // 坐标系类型
      BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL', // iOS坐标系类型
      desiredAccuracy: BMFDesiredAccuracy.best, // 定位精度
      allowsBackgroundLocationUpdates: false, // 是否允许后台定位
      pausesLocationUpdatesAutomatically: false, // 是否自动暂停定位
    );
    return options;
  }

  /// 设置地图参数
  BaiduLocationIOSOption _initAndroidOptions() {
    BaiduLocationIOSOption options = BaiduLocationIOSOption(
      // 位置获取超时时间
      locationTimeout: 10,
      // 获取地址信息超时时间
      reGeocodeTimeout: 10,
      coordType: BMFLocationCoordType.bd09ll,
      desiredAccuracy: BMFDesiredAccuracy.best,
      isNeedNewVersionRgc: true,
      allowsBackgroundLocationUpdates: true,
      distanceFilter: 10,
    );
    return options;
  }

  void locationAction() async {
    /// 设置android端和ios端定位参数
    /// android 端设置定位参数
    /// ios 端设置定位参数
    Map iosMap = _initIOSOptions().getMap();
    Map androidMap = _initAndroidOptions().getMap();

    await _myLocPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 设置地图回调
  void _setupMapCallbacks() {
    _mapController?.setMapDidLoadCallback(
      callback: () {
        ///设置定位参数
        locationAction();

        ///启动定位
        _myLocPlugin.startLocation();
        print('mapDidLoad-地图加载完成');
        _mapController?.showUserLocation(true);
        updatUserLocationDisplayParam();
        // updateUserLocation();
        _mapController?.showUserLocation(true);
        BMFCoordinate coordinate = BMFCoordinate(39.965, 116.404);
        BMFLocation location = BMFLocation(
          coordinate: coordinate,
          altitude: 0,
          horizontalAccuracy: 5,
          verticalAccuracy: -1.0,
          speed: -1.0,
          course: -1.0,
        );
        BMFUserLocation userLocation = BMFUserLocation(location: location);
        _updateUserLocationDisplayParam();
        _myLocPlugin.startLocation();
        _mapController?.updateLocationData(userLocation);
      },
    );

    // ///设置定位参数
    locationAction();

    // ///启动定位
    // _myLocPlugin.startLocation();
    // if (_showUserLocaion) {
    //   _mapController?.showUserLocation(true);
    //   _mapController?.setUserTrackingMode(_userTrackingMode);
    // }

    // if (_showUserLocaion) {
    // _mapController?.showUserLocation(true);
    // _mapController?.setUserTrackingMode(_userTrackingMode);
    // }
    // };
    _myLocPlugin.startLocation();

    _mapController?.setMapDidFinishedRenderCallback(
      callback: (bool success) {
        print('mapDidFinishedReder-地图渲染完成');
        _mapController?.showUserLocation(true);
        _updateUserLocation();
        _updateUserLocationDisplayParam();

        // _(_userLocation.location, _userLocation.longitude);
        // _mapController?.setCenterCoordinate(coordinate, true);
      },
    );

    ///接受定位回调
    _myLocPlugin.seriesLocationCallback(
      callback: (BaiduLocation result) {
        setState(() {
          updateUserLocation(result);
          updateSelfUserLocation(result);
        });
      },
    );
  }

  /// 更新定位图层样式
  void updatUserLocationDisplayParam() {
    // BMFUserLocationDisplayParam displayParam = BMFUserLocationDisplayParam(
    //   locationViewImageNew: 'assets/images/user.png',
    //   locationViewOffsetX: 0,
    //   locationViewOffsetY: 0,
    //   isLocationArrowStyleCustom: true,
    //   accuracyCircleFillColor: Colors.red,
    //   locationViewHierarchy:
    //       BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM,
    //   accuracyCircleBorderWidth: 1,
    //   locationViewCenterGifImageFilePath: 'assets/images/user.png',
    //   locationViewAroundArrowsImage: 'assets/images/user.png',
    //   locationViewImage: 'assets/images/user.png',
    //   isAccuracyCircleShow: true, // 显示精度圈

    //   locationViewCenterImageSizeScale: 1.5,
    //   isRotateAngleValid: true,
    // );

    // _displayParam = displayParam;
    // _mapController?.updateLocationViewWithParam(displayParam);
  }

  /// 更新位置
  void updateSelfUserLocation(BaiduLocation result) {
    if (result.latitude == null || result.longitude == null) return;
    BMFCoordinate coordinate = BMFCoordinate(
      result.latitude!,
      result.longitude!,
    );
    _mapController?.setCenterCoordinate(coordinate, true);
    BMFLocation location = BMFLocation(
      coordinate: coordinate,
      altitude: result.altitude,
      course: result.course,
      accuracy: result.radius,
      horizontalAccuracy: result.horizontalAccuracy,
      verticalAccuracy: result.verticalAccuracy,
    );
    BMFUserLocation userLocation = BMFUserLocation(location: location);
    // _userLocation = userLocation;
    // _mapController?.updateLocationData(_userLocation!);
    setState(() {
      _userLocation = userLocation;
    });

    if (_mapController != null) {
      _mapController!.updateLocationData(userLocation);
      _mapController!.showUserLocation(true);
    }
  }

  /// 添加地图覆盖物
  void _addMapOverlays() {
    _updateUserLocation();
    _updateUserLocationDisplayParam();
    // final BMFMarker marker = BMFMarker(
    //   position: BMFCoordinate(39.928617, 116.40329),
    //   title: '家',
    // );
    // final BMFCircle circle = BMFCircle(
    //   center: BMFCoordinate(39.928617, 116.40329),
    //   radius: 500,
    //   width: 6,
    //   strokeColor: Colors.green,
    //   lineDashType: BMFLineDashType.LineDashTypeSquare,
    // );

    // _overlays.addAll([marker, circle]);
    // _mapController?.addOverlays(_overlays);
  }

  /// 更新用户位置
  void _updateUserLocation() {
    if (_mapController != null) {
      _mapController!.showUserLocation(true);
      final BMFUserLocation userLocation = BMFUserLocation();
      _mapController!.updateLocationData(userLocation);
    }
  }

  // /// 创建用户定位显示参数
  BMFUserLocationDisplayParam _createUserLocationDisplayParam() {
    return BMFUserLocationDisplayParam(
      locationViewImageNew: 'assets/images/user.png',
      locationViewOffsetX: 0,
      locationViewOffsetY: 0,
      isLocationArrowStyleCustom: true,
      accuracyCircleFillColor: Colors.blue,
      locationViewHierarchy:
          BMFLocationViewHierarchy.LOCATION_VIEW_HIERARCHY_BOTTOM,
      accuracyCircleBorderWidth: 4,
      locationViewCenterGifImageFilePath: 'assets/images/user.png',
      locationViewAroundArrowsImage: 'assets/images/user.png',
      locationViewImage: 'assets/images/user.png',
      isAccuracyCircleShow: true, // 显示精度圈

      locationViewCenterImageSizeScale: 4,
      isRotateAngleValid: true,
    );
  }

  /// 更新用户定位显示参数
  void _updateUserLocationDisplayParam() async {
    if (_mapController != null) {
      print('开始更新用户位置显示参数...');
      try {
        final displayParam = _createUserLocationDisplayParam();
        print('显示参数创建完成，准备更新地图视图');
        bool a = await _mapController!.updateLocationViewWithParam(
          displayParam,
        );
        print('用户位置显示参数更新完成~>$a');
      } catch (e, stack) {
        print('更新用户位置显示参数失败: $e');
        print('堆栈跟踪: $stack');
      }
    } else {
      print('错误：地图控制器为空');
    }
  }

  // }
}
